package cn.edu.zime.tjh.iotapp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.edu.zime.tjh.iotapp.api.ApiCallback;
import cn.edu.zime.tjh.iotapp.api.ApiService;

public class TemperatureActivity extends AppCompatActivity {

    private static final String TAG = "BatteryTempActivity";
    private static final int RANGE_LIMIT = 20; // 显示的数据点数量限制
    private static final long UPDATE_INTERVAL = 1000; // 更新频率1秒
    
    private LineChart temperatureChart;
    private TextView temperatureValueText;
    private TableLayout temperatureTable;
    private List<Entry> entries = new ArrayList<>();
    private int tableIndex = 0;
    
    // 定时更新相关
    private Handler updateHandler;
    private Runnable updateRunnable;
    
    // 当前温度值
    private float currentTemperature = 0;
    
    // 电池温度广播接收器
    private BroadcastReceiver batteryReceiver;
    
    // API服务
    private ApiService apiService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_altitude);

        // 初始化API服务
        apiService = ApiService.getInstance();
        
        // 初始化UI
        initUI();
        
        // 设置电池温度监听
        setupBatteryTempMonitor();
        
        // 设置定时更新
        setupTimedUpdates();
    }

    /**
     * 初始化UI组件
     */
    private void initUI() {
        temperatureChart = findViewById(R.id.altitudeChart);
        temperatureValueText = findViewById(R.id.altitudeValueText);
        temperatureTable = findViewById(R.id.altitudeTable);

        // 更新表头
        TableRow headerRow = (TableRow) temperatureTable.getChildAt(0);
        if (headerRow != null && headerRow.getChildCount() >= 2) {
            TextView valueHeader = (TextView) headerRow.getChildAt(1);
            if (valueHeader != null) {
                valueHeader.setText("电池温度(°C)");
            }
        }

        setupChart();
    }
    
    /**
     * 设置电池温度监听
     */
    private void setupBatteryTempMonitor() {
        // 初始化广播接收器
        batteryReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
                    // 获取电池温度，单位为0.1°C，需要除以10获取实际温度
                    int temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
                    float batteryTemp = temp / 10.0f;
                    
                    // 更新当前温度值
                    currentTemperature = batteryTemp;
                    Log.d(TAG, "电池温度更新: " + batteryTemp + "°C");
                }
            }
        };
        
        // 立即获取一次当前温度
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = registerReceiver(batteryReceiver, intentFilter);
        if (batteryStatus != null) {
            int temp = batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
            currentTemperature = temp / 10.0f;
            Log.d(TAG, "初始电池温度: " + currentTemperature + "°C");
        }
    }
    
    /**
     * 设置定时更新
     */
    private void setupTimedUpdates() {
        updateHandler = new Handler(Looper.getMainLooper());
        updateRunnable = new Runnable() {
            @Override
            public void run() {
                // 更新UI显示
                updateTextDisplay(currentTemperature);
                updateChartDisplay(currentTemperature);
                addDataToTable(currentTemperature);
                
                // 上传数据到服务器
                uploadSensorData(currentTemperature);
                
                // 安排下一次更新
                updateHandler.postDelayed(this, UPDATE_INTERVAL);
            }
        };
        
        // 开始定时更新
        updateHandler.postDelayed(updateRunnable, UPDATE_INTERVAL);
    }

    private void setupChart() {
        LineDataSet dataSet = new LineDataSet(entries, "电池温度");
        dataSet.setColors(ColorTemplate.MATERIAL_COLORS);
        dataSet.setValueTextColor(android.R.color.black);
        LineData lineData = new LineData(dataSet);
        temperatureChart.setData(lineData);
        temperatureChart.invalidate();
    }

    @Override
    protected void onResume() {
        super.onResume();
        
        // 注册电池广播接收器
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(batteryReceiver, filter);
        
        // 恢复定时更新
        if (updateHandler != null && updateRunnable != null) {
            updateHandler.postDelayed(updateRunnable, UPDATE_INTERVAL);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        
        // 取消注册广播接收器
        try {
            unregisterReceiver(batteryReceiver);
        } catch (IllegalArgumentException e) {
            // 忽略未注册的异常
            Log.e(TAG, "电池广播接收器未注册: " + e.getMessage());
        }
        
        // 暂停定时更新
        if (updateHandler != null && updateRunnable != null) {
            updateHandler.removeCallbacks(updateRunnable);
        }
    }
    
    /**
     * 更新文本显示
     */
    private void updateTextDisplay(float temperature) {
        temperatureValueText.setText("电池温度: " + temperature + " °C");
    }
    
    /**
     * 更新图表显示
     */
    private void updateChartDisplay(float temperature) {
        entries.add(new Entry(entries.size(), temperature));
        if (entries.size() > RANGE_LIMIT) {
            entries.remove(0);
        }

        LineData lineData = temperatureChart.getData();
        LineDataSet dataSet = (LineDataSet) lineData.getDataSetByIndex(0);
        dataSet.setValues(entries);
        lineData.notifyDataChanged();
        temperatureChart.notifyDataSetChanged();
        temperatureChart.invalidate();
    }

    /**
     * 将数据添加到表格
     */
    private void addDataToTable(float temperature) {
        // 限制表格行数
        if (temperatureTable.getChildCount() > RANGE_LIMIT) {
            temperatureTable.removeViewAt(1); // 保留表头，移除最早的数据行
        }
    
        TableRow row = new TableRow(this);
        TextView indexTextView = new TextView(this);
        indexTextView.setText(String.valueOf(tableIndex++));
        indexTextView.setPadding(8, 8, 8, 8);
        row.addView(indexTextView);

        TextView valueTextView = new TextView(this);
        valueTextView.setText(String.valueOf(temperature));
        valueTextView.setPadding(8, 8, 8, 8);
        row.addView(valueTextView);

        temperatureTable.addView(row);
    }
    
    /**
     * 上传传感器数据到服务器
     */
    private void uploadSensorData(float temperature) {
        try {
            // 构建数据JSON对象 - 按照API文档格式
            JSONObject sensorData = new JSONObject();
            
            // 根据温度设置警报级别
            String alarmLevel = "Normal"; // 注意大写的N
            if (temperature > 40) {
                alarmLevel = "High";  // 高温
            } else if (temperature < 10) {
                alarmLevel = "Low";   // 低温
            }
            
            // 按照API要求的格式设置字段
            sensorData.put("alarm_level", alarmLevel);
            sensorData.put("sensor_type", "battery_temperature");
            sensorData.put("sensor_value", temperature);
            
            // 调用API服务上传数据
            apiService.submitSensorData(sensorData, new ApiCallback() {
                @Override
                public void onSuccess(JSONObject response) {
                    Log.d(TAG, "电池温度数据上传成功: " + response.toString());
                }

                @Override
                public void onFailure(String errorMsg) {
                    Log.e(TAG, "电池温度数据上传失败: " + errorMsg);
                    
                    // 打印完整的请求体，便于调试
                    try {
                        Log.d(TAG, "请求体: " + sensorData.toString(2));
                    } catch (JSONException e) {
                        Log.e(TAG, "JSON格式化失败", e);
                    }
                }
            });
        } catch (JSONException e) {
            Log.e(TAG, "创建电池温度数据JSON失败: " + e.getMessage());
        }
    }
    
    public void back(View V) {
        finish();
    }
}